// gamewindow.cpp
#include "gamewindow.h"
#include <QMessageBox>
#include <QStatusBar>
#include <QDir>
#include <QDebug>

GameWindow::GameWindow(QWidget *parent) : QMainWindow(parent) {
    m_config = new Config(this);
    m_config->load();

    m_gameCore = new GameCore(this);
    m_renderer = new Renderer(this);
    m_renderer->setCellSize(m_config->cellSize());

    m_levelManager = new LevelManager(this);
    // 尝试加载当前目录下的levels文件夹
    if (!m_levelManager->loadLevelList("levels/")) {
        // 如果失败，尝试创建levels文件夹
        QDir().mkdir("levels");
    }

    m_inputHandler = new InputHandler(m_renderer, this);

    initUI();
    initMenu();
    connectSignals();

    // 加载第一关
    if (m_levelManager->totalLevels() > 0) {
        m_levelManager->setLevel(0);  // 有有效关卡，加载第一关
    } else {
        // 无关卡时提示用户
        QMessageBox::warning(this, "提示",
            "未找到有效关卡文件！\n请在程序目录下创建 levels 文件夹，并添加 .map 格式的关卡文件。");
    }

    if (m_levelManager->loadLevelList("levels/")) {
        if (m_levelManager->totalLevels() > 0) {
            m_levelManager->setLevel(0);
            // 打印初始地图数据
            MapData initialMap = m_gameCore->currentMap();
            qDebug() << "初始玩家位置：" << initialMap.playerStartPos;
            // 查找初始箱子位置
            for (int row = 0; row < initialMap.rows; ++row) {
                for (int col = 0; col < initialMap.cols; ++col) {
                    if (initialMap.grid[row][col] == MapElement::Box ||
                        initialMap.grid[row][col] == MapElement::BoxOnTarget) {
                        qDebug() << "初始箱子位置：" << row << "," << col;
                    }
                }
            }
        }
    }
}

GameWindow::~GameWindow() {
    m_config->save();
    delete m_config;
}

void GameWindow::initUI() {
    setCentralWidget(m_renderer);
    setWindowTitle("推箱子");
    resize(m_config->windowSize());
    statusBar()->showMessage("准备就绪");
}

void GameWindow::initMenu() {
    QMenu *gameMenu = menuBar()->addMenu("游戏");

    QAction *restartAction = gameMenu->addAction("重新开始");
    connect(restartAction, &QAction::triggered, m_gameCore, &GameCore::resetLevel);

    QAction *prevLevelAction = gameMenu->addAction("上一关");
    connect(prevLevelAction, &QAction::triggered, m_levelManager, &LevelManager::prevLevel);

    QAction *nextLevelAction = gameMenu->addAction("下一关");
    connect(nextLevelAction, &QAction::triggered, m_levelManager, &LevelManager::nextLevel);

    gameMenu->addSeparator();
    QAction *exitAction = gameMenu->addAction("退出");
    connect(exitAction, &QAction::triggered, this, &QMainWindow::close);

    QMenu *helpMenu = menuBar()->addMenu("帮助");
    QAction *aboutAction = helpMenu->addAction("关于");
    connect(aboutAction, &QAction::triggered, this, &GameWindow::showAboutDialog);
}

void GameWindow::connectSignals() {
    // 输入处理 -> 游戏核心
    connect(m_inputHandler, &InputHandler::moveRequested,
            m_gameCore, &GameCore::movePlayer);
    connect(m_inputHandler, &InputHandler::resetRequested,
            m_gameCore, &GameCore::resetLevel);
    connect(m_inputHandler, &InputHandler::prevLevelRequested,
            m_levelManager, &LevelManager::prevLevel);
    connect(m_inputHandler, &InputHandler::nextLevelRequested,
            m_levelManager, &LevelManager::nextLevel);

    // 关卡管理 -> 游戏核心
    connect(m_levelManager, &LevelManager::levelLoaded,
            m_gameCore, &GameCore::initialize);
    connect(m_levelManager, &LevelManager::levelChanged,
            this, &GameWindow::onLevelChanged);
    connect(m_levelManager, &LevelManager::loadFailed,
            this, &GameWindow::onLoadFailed);

    // 游戏核心 -> 渲染器
    connect(m_gameCore, &GameCore::mapUpdated,
             [this]() {
        m_renderer->setMapData(m_gameCore->currentMap());
        m_renderer->update();  // 强制重绘
    });
    connect(m_gameCore, &GameCore::gameStateChanged,
            this, &GameWindow::onGameStateChanged);
    connect(m_gameCore, &GameCore::moveCountChanged,
            this, [this](int count) {
        statusBar()->showMessage(QString("步数: %1").arg(count));
    });
}

void GameWindow::onGameStateChanged(GameState state) {
    switch (state) {
        case GameState::Completed:
            QMessageBox::information(this, "恭喜", "关卡完成！");
            m_levelManager->nextLevel();
            break;
        case GameState::Running:
            statusBar()->showMessage("游戏中");
            break;
        default: break;
    }
}

void GameWindow::onLevelChanged(int current, int total) {
    setWindowTitle(QString("推箱子 - 第 %1 关 / 共 %2 关").arg(current+1).arg(total));
}

void GameWindow::onLevelLoaded(const MapData &mapData) {
    m_renderer->setMapData(mapData);
    m_renderer->update();
}

void GameWindow::onLoadFailed(const QString &error) {
    QMessageBox::critical(this, "错误", error);
}

void GameWindow::showAboutDialog() {
    QMessageBox::about(this, "关于", "推箱子游戏 v1.0\n基于Qt的经典推箱子实现");
}
